const axios = require('axios');

// 高德地图天气API配置
const AMAP_KEY = '983bac76d802e297528af242df5892f1';
const AMAP_WEATHER_URL = 'https://restapi.amap.com/v3/weather/weatherInfo';
const AMAP_IP_URL = 'https://restapi.amap.com/v3/ip';

/**
 * 通过IP定位获取城市编码
 * @param {string} ip - IP地址（可选）
 * @returns {Promise<string>} 城市编码
 */
async function getCityCodeByIP(ip = '') {
  try {
    const params = {
      key: AMAP_KEY,
      output: 'json'
    };
    
    if (ip) {
      params.ip = ip;
    }
    
    const response = await axios.get(AMAP_IP_URL, { params, timeout: 5000 });
    
    if (response.data.status === '1' && response.data.adcode) {
      return response.data.adcode;
    }
    
    throw new Error('无法获取城市编码');
  } catch (error) {
    console.error('IP定位失败:', error.message);
    return '110000'; // 默认返回北京
  }
}

/**
 * 获取城市天气信息
 * @param {string} city - 城市编码或名称
 * @returns {Promise<Object>} 天气数据
 */
async function getWeatherInfo(city) {
  try {
    const params = {
      key: AMAP_KEY,
      city: city || '110000',
      extensions: 'base',
      output: 'json'
    };
    
    const response = await axios.get(AMAP_WEATHER_URL, { params, timeout: 5000 });
    
    if (response.data.status === '1' && response.data.lives && response.data.lives.length > 0) {
      const weatherData = response.data.lives[0];
      
      return {
        city: weatherData.city,
        weather: weatherData.weather,
        temperature: parseFloat(weatherData.temperature),
        windDirection: weatherData.winddirection,
        windPower: weatherData.windpower,
        humidity: weatherData.humidity,
        reportTime: weatherData.reporttime,
        weatherCondition: mapWeatherCondition(weatherData.weather, parseFloat(weatherData.temperature))
      };
    }
    
    throw new Error('天气数据格式错误');
  } catch (error) {
    console.error('获取天气信息失败:', error.message);
    throw new Error('获取天气信息失败，请稍后重试');
  }
}

/**
 * 根据天气和温度映射天气状况类型
 * @param {string} weather - 天气描述
 * @param {number} temperature - 温度
 * @returns {string} 天气状况类型
 */
function mapWeatherCondition(weather, temperature) {
  if (temperature <= 5) {
    return 'cold';
  }
  
  if (temperature >= 28) {
    return 'hot';
  }
  
  if (weather.includes('雨') || weather.includes('雪')) {
    return 'rainy';
  }
  
  if (weather.includes('晴') || weather.includes('多云')) {
    return 'sunny';
  }
  
  return 'normal';
}

/**
 * 获取天气推荐文案
 * @param {string} weatherCondition - 天气状况类型
 * @param {number} temperature - 温度
 * @returns {string} 推荐文案
 */
function getWeatherRecommendationText(weatherCondition, temperature) {
  const recommendations = {
    cold: `今日温度${temperature}℃，天气寒冷，推荐温补类菜品驱寒暖身`,
    hot: `今日温度${temperature}℃，天气炎热，推荐清爽类菜品消暑解渴`,
    rainy: '今日阴雨天气，推荐热汤类菜品暖胃舒心',
    sunny: '今日天气晴朗，适合品尝各类美食',
    normal: '今日天气适宜，推荐您品尝以下菜品'
  };
  
  return recommendations[weatherCondition] || recommendations.normal;
}

/**
 * 搜索城市（模糊搜索）
 * @param {string} keyword - 城市关键词
 * @returns {Promise<Array>} 城市列表
 */
async function searchCity(keyword) {
  try {
    const response = await axios.get('https://restapi.amap.com/v3/config/district', {
      params: {
        key: AMAP_KEY,
        keywords: keyword,
        subdistrict: 0,
        output: 'json'
      },
      timeout: 5000
    });
    
    if (response.data.status === '1' && response.data.districts) {
      return response.data.districts.map(district => ({
        name: district.name,
        adcode: district.adcode,
        center: district.center
      }));
    }
    
    return [];
  } catch (error) {
    console.error('城市搜索失败:', error.message);
    return [];
  }
}

/**
 * 获取天气图标类型
 * @param {string} weather - 天气描述
 * @returns {string} 图标类型
 */
function getWeatherIconType(weather) {
  if (weather.includes('晴')) return 'sunny';
  if (weather.includes('多云')) return 'cloudy';
  if (weather.includes('阴')) return 'overcast';
  if (weather.includes('雨')) return 'rainy';
  if (weather.includes('雪')) return 'snowy';
  if (weather.includes('雾') || weather.includes('霾')) return 'foggy';
  return 'default';
}

/**
 * 获取完整的天气数据（包含推荐信息）
 * @param {string} city - 城市编码
 * @returns {Promise<Object>} 完整天气数据
 */
async function getCompleteWeatherData(city) {
  try {
    const weatherInfo = await getWeatherInfo(city);
    
    return {
      ...weatherInfo,
      recommendationText: getWeatherRecommendationText(
        weatherInfo.weatherCondition, 
        weatherInfo.temperature
      ),
      iconType: getWeatherIconType(weatherInfo.weather)
    };
  } catch (error) {
    throw error;
  }
}

/**
 * 通过IP自动获取天气（用户端默认调用）
 * @param {string} ip - 用户IP
 * @returns {Promise<Object>} 天气数据
 */
async function getWeatherByIP(ip) {
  try {
    const cityCode = await getCityCodeByIP(ip);
    return await getCompleteWeatherData(cityCode);
  } catch (error) {
    console.error('通过IP获取天气失败:', error.message);
    return await getCompleteWeatherData('110000');
  }
}

/**
 * 缓存天气数据（简单内存缓存）
 */
const weatherCache = new Map();
const CACHE_DURATION = 30 * 60 * 1000; // 30分钟

/**
 * 获取缓存的天气数据
 * @param {string} city - 城市编码
 * @returns {Promise<Object>} 天气数据
 */
async function getCachedWeatherData(city) {
  const cacheKey = `weather_${city}`;
  const cached = weatherCache.get(cacheKey);
  
  if (cached && Date.now() - cached.timestamp < CACHE_DURATION) {
    return cached.data;
  }
  
  const weatherData = await getCompleteWeatherData(city);
  
  weatherCache.set(cacheKey, {
    data: weatherData,
    timestamp: Date.now()
  });
  
  return weatherData;
}

/**
 * 清理过期缓存
 */
function clearExpiredCache() {
  const now = Date.now();
  for (const [key, value] of weatherCache.entries()) {
    if (now - value.timestamp >= CACHE_DURATION) {
      weatherCache.delete(key);
    }
  }
}

// 定时清理缓存（每小时）
setInterval(clearExpiredCache, 60 * 60 * 1000);

module.exports = {
  getWeatherInfo,
  getCityCodeByIP,
  getCompleteWeatherData,
  getWeatherByIP,
  searchCity,
  getWeatherRecommendationText,
  getWeatherIconType,
  mapWeatherCondition,
  getCachedWeatherData
};